package com.example.qihuibao.widget.dialog

import android.text.Editable
import android.view.View
import android.widget.*
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.qihuibao.R
import com.example.qihuibao.base.BaseDialogFragment
import com.example.qihuibao.bean.*
import com.example.qihuibao.constant.Global
import com.example.qihuibao.dao.MyDatabase
import com.example.qihuibao.enum.FlowType
import com.example.qihuibao.enum.Status
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.utils.EnumUtils
import com.example.qihuibao.utils.extension.toast
import com.example.qihuibao.widget.view.CommonRecyclerView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *@author: cww
 *@desc:企业信息操作
 *@date: 5/16/23 10:58 AM
 */
class CanteenInfoQueryDialog() : BaseDialogFragment(R.layout.dialog_canteen_info_query) {
    val empTypeList = mutableListOf<EmpType>()
    var modifing = false
    var isModify = false
    var selectStat:Status? = null
    var selectFlowType:FlowType? = null

    override fun initView() {
        mView?.findViewById<View>(R.id.iv_close)?.setOnClickListener { dismiss() }
        (activity as MainActivity).getMainViewModel().queryCanteenInfo(ReqQueryCanteenInfoBean(Global.canteenId)).observe(this) { it ->
            if (it.RetCode == "0") {
                mView?.findViewById<TextView>(R.id.tv_CantID)?.text = "餐厅ID：${it.CantID}"
                mView?.findViewById<EditText>(R.id.et_CantName)?.text = Editable.Factory.getInstance().newEditable(it.CantName)
                val stat = EnumUtils.getStatus(it.Status?:"0")
                selectStat = stat[0]
                val spStatus = mView?.findViewById<Spinner>(R.id.sp_Status)
                spStatus?.isEnabled = false
                spStatus?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, stat)
                spStatus?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectStat = stat[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                mView?.findViewById<CheckBox>(R.id.cb_ServiceType_1)?.isChecked = EnumUtils.getEnable(it.ServiceType?:"", 1)
                mView?.findViewById<CheckBox>(R.id.cb_ServiceType_2)?.isChecked = EnumUtils.getEnable(it.ServiceType?:"", 2)
                mView?.findViewById<CheckBox>(R.id.cb_ServiceType_3)?.isChecked = EnumUtils.getEnable(it.ServiceType?:"", 3)
                mView?.findViewById<CheckBox>(R.id.cb_ServiceType_4)?.isChecked = EnumUtils.getEnable(it.ServiceType?:"", 4)
                mView?.findViewById<CheckBox>(R.id.cb_ServiceType_6)?.isChecked = EnumUtils.getEnable(it.ServiceType?:"", 6)
                mView?.findViewById<CheckBox>(R.id.cb_ServiceType_7)?.isChecked = EnumUtils.getEnable(it.ServiceType?:"", 7)
                val cb_UseMode_1 = mView?.findViewById<CheckBox>(R.id.cb_UseMode_1)
                val cb_UseMode_2 = mView?.findViewById<CheckBox>(R.id.cb_UseMode_2)
                val cb_UseMode_3 = mView?.findViewById<CheckBox>(R.id.cb_UseMode_3)
                cb_UseMode_1?.isChecked = EnumUtils.getEnable(it.UseMode?:"", 1)
                cb_UseMode_2?.isChecked = EnumUtils.getEnable(it.UseMode?:"", 2)
                cb_UseMode_3?.isChecked = EnumUtils.getEnable(it.UseMode?:"", 3)
                val flowType = EnumUtils.getFlowType(it.FlowType)
                selectFlowType = flowType[0]
                val spFlowtype = mView?.findViewById<Spinner>(R.id.sp_flowtype)
                spFlowtype?.isEnabled = false
                spFlowtype?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, flowType)
                spFlowtype?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        selectFlowType = flowType[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                mView?.findViewById<CheckBox>(R.id.cb_QryBalanceFlag)?.isChecked = it.QryBalanceFlag == "1"
                mView?.findViewById<CheckBox>(R.id.cb_QryConsumeFlag)?.isChecked = it.QryConsumeFlag == "1"
                mView?.findViewById<CheckBox>(R.id.cb_OpenChannel_1)?.isChecked = EnumUtils.getEnable(it.OpenChannel?:"", 1)
                mView?.findViewById<CheckBox>(R.id.cb_OpenChannel_2)?.isChecked = EnumUtils.getEnable(it.OpenChannel?:"", 2)
                mView?.findViewById<CheckBox>(R.id.cb_OpenChannel_5)?.isChecked = EnumUtils.getEnable(it.OpenChannel?:"", 5)
                val orderMode = EnumUtils.getFlowType(it.OrderMode)
                val spOrderMode = mView?.findViewById<Spinner>(R.id.sp_OrderMode)
                spOrderMode?.isEnabled = false
                spOrderMode?.adapter = ArrayAdapter(requireActivity(), android.R.layout.simple_list_item_1, orderMode)
                spOrderMode?.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
                    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                        val select = orderMode[position]
                    }

                    override fun onNothingSelected(parent: AdapterView<*>?) {}
                }
                //
                lifecycleScope.launch {
                    var bean:RspQueryEnterpriseInfoBean? = null
                    withContext(Dispatchers.IO) {
                        bean = MyDatabase.db.enterpriseInfoDao().queryInId(Global.CorpID)
                    }
                    if (!bean?.EmpTypeList.isNullOrEmpty()) {
                        empTypeList.clear()
                        empTypeList.addAll(bean!!.EmpTypeList!!)
                    }
                    mView?.findViewById<CommonRecyclerView>(R.id.rv_EmpTypeList)?.init(
                        R.layout.item_checkbox,
                        LinearLayoutManager(context, RecyclerView.VERTICAL, false),
                        empTypeList,
                        {parent, pos ->
                            if (empTypeList.isNotEmpty()) {
                                (parent as CheckBox).text = empTypeList[pos].EmpTypeName
                                parent.isChecked = hasEmpType(empTypeList[pos], it.EmpTypeList)
                                parent.isEnabled = modifing
                                empTypeList[pos].select = parent.isChecked
                                parent.setOnCheckedChangeListener { buttonView, isChecked -> empTypeList[pos].select = isChecked }
                            }
                        }
                    )
                }

                //
                mView?.findViewById<View>(R.id.tv_modify)?.setOnClickListener {
                    modifing = !modifing
                    mView?.findViewById<TextView>(R.id.tv_modify)?.text = if (modifing) "取消" else "修改"
                    spStatus?.isEnabled = modifing
                    cb_UseMode_1?.isEnabled = modifing
                    cb_UseMode_2?.isEnabled = modifing
                    cb_UseMode_3?.isEnabled = modifing
                    spFlowtype?.isEnabled = modifing
                    mView?.findViewById<CheckBox>(R.id.cb_SecondAccFlag)?.isEnabled = modifing
                    mView?.findViewById<CommonRecyclerView>(R.id.rv_EmpTypeList)?.adapter?.notifyDataSetChanged()
                    if (!modifing) {
                        initView()
                    }
                }
                mView?.findViewById<View>(R.id.tv_update)?.setOnClickListener {
                    modifing = true
                    mView?.findViewById<View>(R.id.tv_modify)?.performClick()
                    updateCanteenInfo()
                }
            }else {
                activity?.toast("查询失败")
            }
        }
    }

    private fun hasEmpType(enterpriseEmpType: EmpType, canteenEmpTypeList:List<EmpType>?): Boolean {
        if (canteenEmpTypeList.isNullOrEmpty()) return false
        for (item in canteenEmpTypeList) {
            if (item.EmpTypeID == enterpriseEmpType.EmpTypeID) {
                return true
            }
        }
        return false
    }

    private fun updateCanteenInfo() {
        val useMode = "${if (mView?.findViewById<CheckBox>(R.id.cb_UseMode_3)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_UseMode_2)?.isChecked == true) "1" else "0"}${if (mView?.findViewById<CheckBox>(R.id.cb_UseMode_1)?.isChecked == true) "1" else "0"}"
        val secondAccFlag = if (mView?.findViewById<CheckBox>(R.id.cb_SecondAccFlag)?.isChecked == true) "1" else "0"
        val reqEmpTypes = mutableListOf<EmpType>()
        for (item in empTypeList) {
            if (item.select) {
                reqEmpTypes.add(EmpType(item.EmpTypeID!!))
            }
        }
        val req = ReqUpdateCanteenInfoBean(CantID = Global.canteenId, selectStat?.value?:"0", useMode, selectFlowType?.value?:"0", secondAccFlag, reqEmpTypes)
        (activity as MainActivity).getMainViewModel().updateCanteenInfo(req).observe(this) {
            activity?.toast("${if (it.RetCode == "0") "更新成功" else "更新失败：${it.RetMsg}"}")
            initView()
        }
    }

}